import { req } from "@/common/methods";
import { useEffect, useState } from "react";
import {
  Modal,
  Card,
  Typography,
  Divider,
  Switch,
  Space,
  DatePicker,
} from "antd";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";

import Loading from "@/components/Loading/index.tsx";

import styles from "./index.module.scss";

import Detail from "./Detail.tsx";

import locale from "antd/es/date-picker/locale/zh_CN";
import "dayjs/locale/zh-cn";
import dayjs from "dayjs";

const { Title } = Typography;

const showDocCategory = (method, isIn) => {
  let res = "";
  switch (method) {
    case 10:
      res = isIn ? "进货单" : "退货单";
      break;
    case 20:
      res = isIn ? "收回单" : "领用单";
      break;
    case 30:
      res = "盘点单";
      break;
    default:
      res = "未知单据";
  }
  return res;
};
const depart = {};
const suppliers = {};

const History = () => {
  const [loading, setLoading] = useState(true);
  const [dataDoc, setDataDoc] = useState([]);
  const [showMonth, setShowMonth] = useState(
    (() => {
      const date = new Date();
      return `${date.getFullYear()}-${("" + (date.getMonth() + 1)).padStart(
        2,
        "0"
      )}`;
    })()
  );
  const [hiddenInventory, setHiddenInventory] = useState(true);
  const fetchDataDoc = () => {
    setLoading(true);
    req("/api/depart/get")
      .then((data) => {
        data.forEach((item) => (depart[item.id] = item.name));
        return req("/api/suppliers/get");
      })
      .then((data) => {
        data.forEach((item) => (suppliers[item.id] = item.name));
        return req("/api/storage/all_doc", {
          noInventory: hiddenInventory ? "1" : "0",
          month: showMonth,
        });
      })
      .then((data) => {
        const dateArr = data
          .map((item) => ("" + item.time).substring(0, 10))
          .filter((item1, index1, arr1) => arr1.indexOf(item1) === index1);
        const res = dateArr.map((item) => ({
          date: item,
          children:
            data.filter(
              (item1) => ("" + item1.time).substring(0, 10) === item
            ) || [],
        }));
        setDataDoc(res);
        setLoading(false);
      })
      .catch((error) =>
        Modal.error({
          title: "无法获取初始数据",
          content: <>无法获取初始数据。请检查，{"" + error}</>,
        })
      );
  };
  useEffect(() => {
    fetchDataDoc();
  }, [hiddenInventory, showMonth]);
  return (
    <>
      <div className={styles["toolbar-package"]}>
        <DatePicker
          defaultValue={dayjs(showMonth)}
          locale={locale}
          onChange={(date, dateString) => {
            setShowMonth(dateString);
          }}
          picker="month"
        />{" "}
        <Space>
          <span>隐藏盘点单</span>
          <Switch
            checkedChildren={<CheckOutlined />}
            unCheckedChildren={<CloseOutlined />}
            checked={hiddenInventory}
            onClick={() => {
              setHiddenInventory(!hiddenInventory);
            }}
          />
        </Space>
      </div>
      <Divider />
      {loading ? (
        <Loading />
      ) : (
        <div>
          {dataDoc.map((item) => (
            <div key={item.date}>
              <Title level={3}>{item.date}</Title>
              <div
                className={styles["card-package"]}
                style={{ display: "flex" }}
              >
                {item.children.map((item1) => {
                  return (
                    <Card
                      title={
                        <>
                          {showDocCategory(item1.method, item1.isIn)}
                          {item1.method !== 30 ? (
                            <span style={{ color: "red" }}>
                              <span
                                style={{ color: item1.isIn ? "blue" : "green" }}
                              >
                                ({item1.isIn ? "入库" : "出库"})
                              </span>
                            </span>
                          ) : (
                            ""
                          )}
                        </>
                      }
                      extra={
                        <span style={{ opacity: 0.5 }}>共{item1.count}项</span>
                      }
                      key={item1.doc_id}
                      className={styles["each-card"]}
                      style={{
                        backgroundColor: {
                          10: item1.isIn ? "#00aaff33" : "#77777733",
                          20: item1.isIn ? "#ff33ff33" : "#00ff0033",
                          30: "#ff000033",
                        }[item1.method],
                      }}
                      onClick={() =>
                        Modal.info({
                          title: `${item1.doc_id} - ${
                            item1.method === 30
                              ? "盘点"
                              : item1.isIn
                              ? "入库"
                              : "出库"
                          }单详情`,
                          content: (
                            <>
                              <Detail
                                item={item1}
                                depart={depart}
                                suppliers={suppliers}
                              />
                            </>
                          ),
                          width: 900,
                        })
                      }
                    >
                      {/* <Title level={4}>{showDocCategory(item1.method,item1.isIn)}{item1.method !== 30 ? <span style={{color:'red'}}>({item1.isIn?'入库':'出库'})</span> : ''}</Title> */}
                      <ul>
                        <li>单号:{item1.doc_id}</li>
                        <li>时间:{item1.time}</li>
                        <li>
                          {item1.method === 10 ? "供货商" : "部门"}:
                          {item1.method === 10
                            ? suppliers[item1.depart] || "-"
                            : depart[item1.depart] || "-"}
                        </li>
                        <li>
                          {item1.method === 10 ? "进货人" : "申请人"}:
                          {item1.requ}
                        </li>
                        <li>
                          {item1.method === 10 ? "确认人" : "领用人"}:
                          {item1.empl}
                        </li>
                      </ul>
                    </Card>
                  );
                })}
              </div>
              <Divider />
            </div>
          ))}
        </div>
      )}
    </>
  );
  // return <pre>{JSON.stringify(dataDoc,null,2)}</pre>
};
export default History;
